<?php

namespace App\Http\Requests\Admin;

use App\Models\Role;
use App\Models\Section;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class SectionRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method()) {
            case 'POST':
                return [
                    'name' => ['required', 'min:2', 'max:20', function ($attr, $value, $fail) {
                        $data = Section::query()
                            ->where('pid', request()->input('pid'))
                            ->where('name', $value)
                            ->get()
                            ->toArray();
                        if (!empty($data)) {
                            $fail('同级部门下，不允许有相同名称');
                        }
                    }],
                    'status' => 'required|in:0,1',
                    'pid' => 'nullable|numeric'
                ];
            case 'PUT':
                return [
                    'name' => ['required', 'min:2', 'max:20',function ($attr, $value, $fail) {

                        $thisSection = Section::query()
                            ->where('id' ,$this->route()->parameter('section')->id)
                            ->first()
                            ->toArray();

                        $data = Section::query()
                            ->where('pid', request()->input('pid'))
                            ->where('name', $value)
                            ->get()
                            ->toArray();

                        if (!empty($data) && $value != $thisSection['name']) {
                            $fail('同级部门，不允许有相同名称');
                        }
                    }],
                    'status' => 'required|in:0,1',
                ];
        }
    }
}
